package cn.edu.scau.serviceImpl;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Date;
import java.util.List;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import cn.edu.scau.Utils.SendEmailUtil;
import cn.edu.scau.dao.UserDao;
import cn.edu.scau.entity.Blog;
import cn.edu.scau.entity.User;
import cn.edu.scau.service.UserService;

@Service("userServiceImpl")
public class UserServiceImpl  extends BaseServiceImpl<User> implements UserService {
	
	@Resource(name="userDaoImpl")
	UserDao userDao;
	
	private static final Integer PAGESiZE=4;
	
	/**
	 * 注册
	 */
	public Integer registerTheUser(User user) {
		
		String userEmail = user.getAccount();
		String password = user.getPassword();
		List<User> users = userDao.findAll(User.class);
		if(checkEmail(userEmail)){
			if(password.length()<6){
				//2代表密码的长度小于6
				return 2;
			}else{
				if(users.isEmpty()||users==null){
					password = MD5(password);
					user.setPassword(password);
					user.setCreateTime(new Date());
					userDao.save(user);
					//注册成功，准备激活
					return 3;
				}else{
					for(int i=0;i<users.size();i++){
						if(users.get(i).getAccount().equals(user.getAccount())){
							//邮箱已经被注册过了
							return 4;
						}
					}
					//注册成功
					password = MD5(password);
					user.setPassword(password);
					user.setCreateTime(new Date());
					userDao.save(user);
					return 3;
				}
			}
		}else{
			//1代表邮箱格式不正确
			return 1;
		}
	}
	
	/**
	 * 登录
	 */
	public Integer loginTheUser(String picCode, String checkCode,HttpServletRequest req,HttpServletResponse resp) throws UnsupportedEncodingException {
		String loginEmail = req.getParameter("account");
		String password = req.getParameter("password");
		if(checkPicCode(picCode, checkCode)){
			List<User> users = userDao.findAll(User.class);
			if(users.isEmpty()||users==null){
				//代表邮箱密码错误
				return 1;
			}else{
				for(int i=0;i<users.size();i++){
					if(users.get(i).getAccount().equals(loginEmail)
							&&MD5(password).equals(users.get(i).getPassword())){
						if(users.get(i).isStatus()){
							User user = users.get(i);
							Cookie cookieForUserId = new Cookie("userId",URLEncoder.encode(user.getUserId().toString(), "UTF-8"));
							Cookie cookieForAccount = new Cookie("account",user.getAccount());
							Cookie cookieForNickName = new Cookie("nickName",URLEncoder.encode(user.getNickName(), "UTF-8"));
							Cookie cookieForHeadPicture= new Cookie("headPicture",user.getHeadImage());
							cookieForUserId.setPath("/");
							cookieForAccount.setPath("/");
							cookieForNickName.setPath("/");
							cookieForHeadPicture.setPath("/");
							resp.addCookie(cookieForHeadPicture);
							resp.addCookie(cookieForUserId);
							resp.addCookie(cookieForAccount);
							resp.addCookie(cookieForNickName);
							//登录成功
							return 2;
						}else{
							//还没被激活
							sendEmail(users.get(i).getUserId());
							return 3;
						}
					}
				}
				//代表邮箱密码错误
				return 1;
			}
		}else{
			//验证码错误
			return 4;
		}
	}
	
	/**
	 * 更新用户的信息
	 */
	public boolean updateTheUserMessage(Integer userId, User updateUser,HttpServletResponse resp) throws UnsupportedEncodingException {
		
		User user = userDao.find(User.class, userId);
		if(user==null){
			//用户不存在
			return false;
		}else{	
		//修改成功
		user.setNickName(updateUser.getNickName());
		user.setAdress(updateUser.getAdress());
		user.setHobby(updateUser.getHobby());
		user.setSex(updateUser.getSex());
		user.setJob(updateUser.getJob());
		user.setIntroduction(updateUser.getIntroduction());
		userDao.update(user);
		Cookie cookieForNickName = new Cookie("nickName",URLEncoder.encode(user.getNickName(), "UTF-8"));
		cookieForNickName.setPath("/");
		resp.addCookie(cookieForNickName);
		return true;
		}
	
	}
	/**
	 * 发送邮件
	 */
	public void sendEmail(Integer userId) {
		User user = userDao.find(User.class, userId);
		StringBuffer sb=new StringBuffer("点击下面链接激活账号</br>");  
        sb.append("<a href=\"http://yuanwutou.ngrok.cc/MicroBlog/CheckBeActive?id="+userId);  
        sb.append("\">点击此处激活您的账号!");
        sb.append("</a>");
        SendEmailUtil.send(user.getAccount(), sb.toString());
        System.out.println("发送邮件！");
	}
	
	/**
	 * 激活账号检验
	 */
	public Integer checkBeActive(Integer userId) {
		User user = userDao.find(User.class, userId);
		if(user!=null){
			if(!user.isStatus()){
				Date currentTime = new Date();
				if(currentTime.before(user.getLastActivateTime())){
					user.setStatus(true);
					userDao.update(user);
					//激活成功
					return 4;
				}else{
					//代表激活过期，需重新注册
					userDao.delete(User.class, userId);
					return 2;
				}
			}else{
				//已经激活了
				return 3;
			}
		}else{
			//还没有注册
			return 1;
		}
	}
	/**
	 * MD5加密
	 */
	public String MD5(String password) {
		byte[] result = null;  
		try {  
            MessageDigest md = MessageDigest.getInstance("MD5");  
            md.reset();  
            md.update(password.getBytes("UTF-8"));  
            result = md.digest();  
        } catch (NoSuchAlgorithmException e) {  
            e.printStackTrace();  
        } catch (UnsupportedEncodingException e) {  
            e.printStackTrace();  
        }  
		byte[] data = result;  
        StringBuffer hexString = new StringBuffer();  
        for (int i = 0; i < data.length; i++) {  
            String hex = Integer.toHexString(0xff & data[i]);  
            if (hex.length() == 1) {  
                hexString.append('0');  
            }    
            hexString.append(hex);  
        }  
        return hexString.toString();
	}
	/**
	 * 生成验证码
	 */
	public void picCode(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse)
			throws IOException {
		BufferedImage bi = new BufferedImage(120, 22, BufferedImage.TYPE_INT_RGB);
		Graphics g = bi.getGraphics();
		Color c = new Color(192, 192,192);
		g.setColor(c);
		g.fillRect(0, 0, 120, 22);
		char[] ch = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789".toCharArray();
		Random random = new Random();
		int length = ch.length;
		int index;
		StringBuffer sb  = new StringBuffer();
		for(int i=0;i<6;i++){
			index = random.nextInt(length);
			g.setColor(new Color(random.nextInt(88),random.nextInt(188),random.nextInt(255)));
			g.drawString(ch[index]+"",i*15+10, 18);
			sb.append(ch[index]);
		}
		httpServletRequest.getSession().setAttribute("picCode",sb.toString());
		ImageIO.write(bi,"JPG",httpServletResponse.getOutputStream());
	}
	/**
	 * 用户输入的验证码检验
	 */
	public boolean checkPicCode(String picCode, String checkCode) {
		String upperCaseCheckCode = checkCode.toUpperCase();
		if(upperCaseCheckCode.equals(picCode)){
			return true;
		}else{
			return false;
		}
	}
	/**
	 * 检查邮箱的格式
	 */
	public boolean checkEmail(String userEmail) {
		boolean flag = false;
	    try{
	    	String check = "^([a-zA-Z0-9]+[_|_|.]?)*[a-zA-Z0-9]+@([a-zA-Z0-9]+[_|_|.]?)*[a-zA-Z0-9]+.[a-zA-Z]{2,4}$";
	        Pattern regex = Pattern.compile(check);
	        Matcher matcher = regex.matcher(userEmail);
	        flag = matcher.matches();
	        }catch(Exception e){
	        	flag = false;
	        }
	       return flag;
	}
	/**
	 * 更改头像
	 */
	public Integer changeTheUserHeadPicture(Integer userId, MultipartFile[] files, HttpServletRequest req,HttpServletResponse resp)
			throws Throwable {
		User user = userDao.find(User.class, userId);
		if(user==null){
			//用户不存在
			return 1;
		}else{
			if(files[0].isEmpty()){
				//上传的头像文件为空
				return 2;
			}else{
				
				String headPicturePath = (String)this.saveFiles(files, req).get(0);
				user.setHeadImage(headPicturePath);
				userDao.update(user);
				Cookie cookieForHeadPicture= new Cookie("headPicture",headPicturePath);
				cookieForHeadPicture.setPath("/");
				resp.addCookie(cookieForHeadPicture);
				//头像修改成功
				return 3;
			}
		} 
	}
	/**
	 * 查找用户
	 */
	public User findUser(Integer userId){
		return userDao.find(User.class , userId);
	}
	/**
	 * 根据类型查找与用户有关的微博
	 */
	public List<Blog> findUserBlogByType(Integer userId, Integer pageNo, Integer type) {
		return userDao.findUserBlogsByType(userId, pageNo,PAGESiZE, type);
	}
	/**
	 * 根据类型查找与用户有关的微博的最大页数
	 */
	public long getBlogsMaxPageByType(Integer userId, Integer type) {
		return userDao.getBlogsMaxPageByType(userId, PAGESiZE, type);
	}
	/**
	 * 添加博客
	 */
	public void addUserBlog(Integer userId, Blog blog) {
		userDao.addUserBlog(userId, blog);
	}
	/**
	 * 添加收藏博客
	 */
	public boolean addUserColBlog(Integer userId, Integer blogId) {
		return userDao.addUserColBlog(userId, blogId);
	}
	/**
	 * 根据类型删除与用户有关的微博
	 */
	public boolean deleteBlogByType(Integer userId, Integer blogId, Integer type) {
		return userDao.deleteBlogByType(userId, blogId, type);
	}

}
